package Map

import (
	"sanguo/cluster"
	codecs "sanguo/codec/cs"
	"sanguo/node/common/transaction"
	"sanguo/node/node_game"
	"sanguo/node/node_game/module/role"
	"sanguo/node/node_game/user"
	cs_message "sanguo/protocol/cs/message"
	ss_message "sanguo/protocol/ss/message"
	"time"

	"github.com/golang/protobuf/proto"
)

type transactionStartAoi struct {
	transaction.TransactionBase
	user     *user.User
	req      *codecs.Message
	resp     *cs_message.StartAoiToC
	errcode  cs_message.EnumType
	node_map cluster.PeerID
}

func (this *transactionStartAoi) GetModuleName() string {
	return "Map"
}

func (this *transactionStartAoi) GetReplyMsg() proto.Message {
	return &cs_message.StartAoiToC{}
}

func (this *transactionStartAoi) SetExpiredTime(expired time.Time) {
	this.Expired = expired
}

func (this *transactionStartAoi) GetExpiredTime() time.Time {
	return this.Expired
}

func (this *transactionStartAoi) Begin() {
	this.resp = &cs_message.StartAoiToC{}
	roleModule := this.user.GetModuleByName("role").(*role.RoleModule)
	role := roleModule.CurrentRole()

	if role.NodeMap == nil {
		node_game.Infoln(role.GetUserID(), role.GetID(), "fail no map enter")
		this.errcode = cs_message.EnumType_ERROR
		this.user.EndTrans(this)
		return
	}

	startAoi := &ss_message.StartAoi{
		UserID:  proto.String(this.user.GetUserID()),
		MapType: proto.Int32(role.GetMapID()),
	}
	cluster.PostMessage(*role.NodeMap, startAoi)

	node_game.Infoln(role.GetUserID(), role.GetID(), "Strat Aoi OK")
	this.errcode = cs_message.EnumType_OK
	this.user.EndTrans(this)
}

func (this *transactionStartAoi) End() {
	this.resp.Errcode = cs_message.EnumType(this.errcode).Enum()
	this.user.Reply(this.req.GetSeriNo(), this.resp)
}

func (this *transactionStartAoi) Timeout() {
	this.resp.Errcode = cs_message.EnumType(cs_message.EnumType_RETRY).Enum()
	this.user.EndTrans(this)
}

func init() {
	user.RegisterTransFunc(&cs_message.StartAoiToS{}, func(user *user.User, msg *codecs.Message) transaction.Transaction {
		return &transactionStartAoi{
			user: user,
			req:  msg,
		}
	})
}
